<template>
  <div class="timing">
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline queryFrom">
          <el-form-item label="名称">
            <el-input v-model="formInline.firmName" clearable placeholder="" />
          </el-form-item>
          <el-form-item>
            <el-button plain @click="getUserList"><Icon type="ios-search" />查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-button type="primary" @click="addUser('add')"><Icon type="md-add" />创建API应用</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <ykhttb
      ref="httbRef"
      :table-col="tabUserList"
      width="180"
      :table-data="tableUserData"
      @lookDoc="lookDoc"
      @deleteSelectData="deleteSelectData"
      @refresh="getUserList"
    />
    <!-- 分页 -->
    <div style="text-align:right;margin-top:10px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :close-on-click-modal="false" :title="title" width="50%" :visible.sync="dialogTableVisible">
      <!-- 名称和路径必输 -->
      <el-form v-if="dialogTableVisible" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm autoClass">
        <el-form-item label="服务对象" prop="appKey">
          <el-select v-model="ruleForm['appKey']" multiple>
            <el-option v-for="(item,index) in appKeyOptions" :key="index" :value="item.appKey" :label="item.serverObjectName" />
          </el-select>
        </el-form-item>
        <el-form-item label="API类型" prop="apiType">
          <el-select v-model="ruleForm['apiType']">
            <el-option value="自定义API" label="自定义API" />
            <el-option value="硬编码API" label="硬编码API" />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="文档地址" prop="fireAddress">-->
<!--          <el-input v-model="ruleForm['fireAddress']" clearable placeholder="请输入文档地址" />-->
<!--        </el-form-item>-->

        <el-form-item v-if="ruleForm['apiType']=='自定义API'" label="名称" prop="apiName">
          <el-input v-model="ruleForm['apiName']" clearable placeholder="" />
        </el-form-item>
        <el-form-item v-if="ruleForm['apiType']=='自定义API'" label="路径" prop="path">
          <el-input v-model="ruleForm['path']" clearable placeholder=""><template slot="prepend">/open-api/</template></el-input>
        </el-form-item>

        <el-form-item v-if="ruleForm['apiType']=='自定义API'" label="SQL" prop="datasourceId" style="width:100%;height: 300px;">
          <div style="width:100%;display:flex;">
            <div style="width:24%">
              <el-select v-model="ruleForm['datasourceId']" @change="getZtreeList">
                <el-option
                  v-for="item in sqloptions"
                  :key="item.id"
                  :label="item.databaseName"
                  :value="item.id"
                />
              </el-select>
              <div style="width:100%;height:270px;overflow-y: scroll;border:1px solid #eee">
                <el-tree :data="dataList" :highlight-current="true" :props="defaultProps" @node-click="handleNodeClick" />
              </div>
            </div>
            <div style="width:76%;border:1px solid #eee;">
              <quillEditor ref="quillEditor" v-model="ruleForm['sqlData']" :sql-value="sqlValue" />
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="ruleForm['apiType']=='自定义API'" label="数据模型" prop="modelId">
          <el-select v-model="ruleForm.modelId" @change="getIdName(ruleForm,'modelName',dataModuleOptionsList)">
            <el-option v-for="(item,index) in dataModuleOptionsList" :key="index" :value="item.id" :label="item.dataModelName" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm['apiType']=='自定义API'" label="脱敏脱密规则" prop="desensitizationId">
          <el-select v-model="ruleForm.desensitizationId" @change="getIdName(ruleForm,'desensitizationName',gzOptionsList)">
            <el-option v-for="(item,index) in gzOptionsList" :key="index" :value="item.id" :label="item.desensitizationName" />
          </el-select>
        </el-form-item>

        <el-divider v-show="ruleForm['apiType']=='硬编码API'" />
        <el-form-item v-show="ruleForm['apiType']=='硬编码API'" label="接口描述" class="autoLabel">
          <el-input v-model="sk_like_apiName" clearable placeholder="" />
          <el-button plain @click="queryallApipage(sk_like_apiName)"><Icon type="ios-search" />查询</el-button>
        </el-form-item>
        <el-form-item v-show="ruleForm['apiType']=='硬编码API'" label="" prop="" style="width: 100%;">
          <el-table
            :data="tableData"
            header-cell-style="background-color:#f2f5f8; color: #5a516e"
            height="350"
            border
            :highlight-current-row="true"
            style="width: 100%"
          >
            <el-table-column label="选择" width="50" align="center">
              <template slot-scope="scope">
                <el-radio v-model="selectedRow" :label="scope.row" @input="handleRowClick(scope.row)">{{ '' }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="apiName"
              label="API名称"
            />
            <el-table-column
              align="center"
              prop="methodName"
              label="函数名称"
            />
            <el-table-column
              align="center"
              prop="path"
              label="接口地址"
            />
            <el-table-column
              align="center"
              prop="requestType"
              label="请求类型"
            />
          </el-table>
          <!-- 分页 -->
          <div style="text-align:right;margin-top:10px;">
            <el-pagination
              :current-page="pageIndex2"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize2"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total2"
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
            />
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button type="primary" @click="submitForm('ruleForm')">{{ btnStr }}</el-button>
        <el-button @click="resetForm('return')">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="45%">
      <div v-if="dialogVisible" style="width:760px;height:650px;overflow: scroll;text-align: center;margin: 0 auto;">
        <img src="http://58.16.4.102:27071/huatai/2025-06-18/%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3.jpg" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiInfopage, apiInfosave, apiInfodelete, dataSourcepage, dataSourcequeryAllTableName, dataSourcegetAllColumns,
  dataModeldatagetList, desensitizationrulegetList, serverObjectpage, allApipage
} from '@/api/zt/index'
import experiment from '@/mixins/experiment'

import quillEditor from './sqlEditDEMO.vue'
export default {
  components: {
    quillEditor
  },
  mixins: [experiment],
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error('请选择服务对象'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible:false,
      sk_like_apiName: '',
      selectedRow: null,
      pageIndex2: 1,
      pageSize2: 10,
      tableData: [],
      appKeyOptions: [],
      sqlValue: '',
      dataModuleOptionsList: [],
      gzOptionsList: [],
      sqloptions: [],
      dataList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      title: '新增',
      rules: {
        appKey: [
          { required: true, validator: validatePass2, trigger: 'change' }
        ],
        apiName: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ],
        path: [
          { required: true, message: '请输入路径', trigger: 'change' }
        ],
        datasourceId: [
          { required: true, message: '请选择SQL', trigger: 'change' }
        ],
        modelId: [
          { required: true, message: '请选择数据模型', trigger: 'change' }
        ],
        apiType: [
          { required: true, message: '请选择API类型', trigger: 'change' }
        ],
        fireAddress: [
          { required: true, message: '请输入文档地址', trigger: 'change' }
        ]
      },
      dialogTableVisible: false,
      ruleForm: {
        'apiType': '',
        'apiName': '',
        'appKey': [],
        'createTime': '',
        'datasourceId': '',
        'desensitizationId': 0,
        'desensitizationName': '',
        'fireAddress': '',
        'id': 0,
        'modelId': 0,
        'modelName': '',
        'objectId': '',
        'params': '',
        'path': '',
        'spare1': '',
        'spare2': '',
        'sqlData': '',
        'updateTime': ''
      },
      userId: '',
      formInline: {
        firmName: ''
      },
      addParms: [],
      tableUserData: [],
      tabUserList: [
        {
          key: 'apiName',
          title: 'API名称'
        },
        {
          key: 'path',
          title: 'API地址'
        },
        {
          key: 'params',
          title: '参数'
        },
        {
          key: 'createTime',
          title: '创建时间'
        }
        // {
        //   key: 'state',
        //   title: '状态'
        // }
      ],
      total: 0,
      total2: 0,
      size: 10,
      page: 1
    }
  },
  created() {
    serverObjectpage({
      'pageIndex': 1,
      'pageSize': 11111,
      'or_orderby_createTime': '',
      'sk_like_serverObjectName': ''
    }).then(res => {
      this.appKeyOptions = res.data.records
    })
    dataSourcepage({
      'pageIndex': 1,
      'or_orderby_createTime': 'dsc',
      'sk_like_databaseName': '',
      'pageSize': 1000
    }).then(res => {
      this.sqloptions = res.data.records
    })
    dataModeldatagetList({
      'pageIndex': 1,
      'dataModelName': '',
      'dataModelTypeId': null,
      'pageSize': 1000
    }).then(res => {
      this.dataModuleOptionsList = res.data.records
    })

    desensitizationrulegetList({
      'pageIndex': 1,
      'pageSize': 1000,
      'desensitizationName': ''
    }).then(res => {
      this.gzOptionsList = res.data.records
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.getUserList()
      this.queryallApipage('')
    })
  },
  methods: {
    lookDoc() {
      this.dialogVisible = true
    },
    handleRowClick(row) {
      this.selectedRow = row
    },
    queryallApipage(v) {
      allApipage({
        or_orderby_createTime: 'dsc',
        pageIndex: this.pageIndex2,
        pageSize: this.pageSize2,
        sk_like_apiName: v
      }).then(res => {
        this.tableData = res.data.records
        this.total2 = res.data.total
      })
    },
    getIdName(v, setNamekeyStr, options) {
      options.forEach((item, index) => {
        if (setNamekeyStr == 'modelName' && v.modelId == item.id) {
          v.modelName = item.dataModelName
        } else if (setNamekeyStr == 'desensitizationName' && v.desensitizationId == item.id) {
          v.desensitizationName = item.desensitizationName
        }
      })
    },
    handleNodeClick(data) {
      if (data.hasOwnProperty('children')) {
        dataSourcegetAllColumns({
          dataSourceId: this.ruleForm['datasourceId'],
          tableName: data.label
        }).then(res => {
          this.dataList.forEach((item, index) => {
            if (item.label == data.label) {
              item.children = res.data || []
            }
          })
        })
      }
    },
    getZtreeList() {
      dataSourcequeryAllTableName({ dataSourceId: this.ruleForm['datasourceId'] }).then(res => {
        const arr = res.data || []
        this.dataList = []
        arr.forEach((item, index) => {
          this.dataList.push({
            label: item,
            children: []
          })
        })
      })
    },
    deleteSelectData(v) {
      const ids = [v.id]
      apiInfodelete(ids).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    inspectformdat2(v) {
      let flag = true
      if (v.length > 0) {
        for (let i = 0; i < v.length; i++) {
          if (!v[i]['modelId']) {
            flag = false
            this.$message.error(`请把第${i + 1}条数据填写完整！`)
            break
          }
        }
      }
      return flag
    },
    commitFromData() {
      if (this.title == '新增') {
        delete this.ruleForm.id
      }
      if (this.ruleForm['apiType'] == '硬编码API' && this.selectedRow == null) {
        this.$message.error('请先选择列表数据')
        return
      }
      if (this.ruleForm.appKey.length != 0) {
        this.ruleForm.objectId = []
        this.appKeyOptions.forEach((item, index) => {
          if (this.ruleForm.appKey.includes(item.appKey)) {
            this.ruleForm.objectId.push(item.id)
          }
        })
      }
      // this.ruleForm.objectId = JSON.stringify(this.ruleForm.objectId)

      const newsruleForm = JSON.parse(JSON.stringify(this.ruleForm))
      console.log(JSON.parse(JSON.stringify(newsruleForm)))
      newsruleForm.appKey = JSON.stringify(newsruleForm.appKey)
      newsruleForm.objectId = JSON.stringify(newsruleForm.objectId)
      if (this.ruleForm['apiType'] == '自定义API') {
        const sqlV = this.$refs.quillEditor.returnSqlVal()
        newsruleForm.sqlData = sqlV
        if (!sqlV) {
          this.$message.error('请输入SQL语句')
          return
        }
      } else {
        newsruleForm.apiName = this.selectedRow.apiName
        newsruleForm.path = this.selectedRow.path
      }
      console.log(newsruleForm)
      // return
      apiInfosave(newsruleForm).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleSizeChange(v) {
      this.page = 1
      this.size = v
      this.getUserList()
    },
    handleCurrentChange(v) {
      this.page = v
      this.getUserList()
    },

    handleSizeChange2(v) {
      this.pageIndex2 = 1
      this.pageSize2 = v
      this.queryallApipage(this.sk_like_apiName)
    },
    handleCurrentChange2(v) {
      this.pageIndex2 = v
      this.queryallApipage(this.sk_like_apiName)
    },

    // 获取用户列表
    getUserList() {
      this.dialogTableVisible = false
      this.$refs.httbRef.isShowLoading(true)
      apiInfopage({
        'pageSize': this.size,
        'pageIndex': this.page,
        'or_orderby_createTime': 'dsc',
        'sk_like_apiName': this.formInline.firmName
      }).then(res => {
        this.tableUserData = res.data.records
        this.total = res.data.total
        this.$refs.httbRef.isShowLoading(false)
      })
    }
  }
}
</script>

  <style lang="scss" scoped>
  >>>::-webkit-scrollbar{
    display: none;
}
  >>>.autoLabel{
    .el-input{
      width: 80%;
    }
  }
  >>>.cell{
    overflow: hidden;
    display: -webkit-box;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    white-space: normal;
  }
    >>>.CodeMirror-sizer{
    // min-height: 300px !important;
    // pre{
    //   min-height: 300px !important;
    // }
  }
    .addcs{
      display: flex;
      flex-direction: row;
      margin-bottom: 10px;
    }
    .addcs>p{
      width:48%;
    }
    .addcs2>p{
      width:48%;
    }
    .addcs2 .el-select {
      display: inline-block;
      width:350px;
    }
    .autoInput{
      display: inline-block;
      width: 70%;
    }
    .infoTitle{
      border-bottom:1px solid #e5e5e5;
      margin-bottom: 30px;
      position: relative;
    }
    .infoTitle>span{
      position: absolute;
      left: 20px;
      background: #fff;
      width:80px;
      top:-15px;
      height:30px;
      text-align: center;
      line-height: 30px;
    }
      .el-select{
        width:100%;
      }
      .timing{
        background:#fff;
        padding:20px;
      }
      .autoClass{
        display:flex;
        flex-direction:row;
        flex-wrap:wrap;
        justify-content: space-between;
        .el-form-item{
            width:50%;
        }
  }
    </style>
